package com.example.controller;

import cn.hutool.core.io.FileUtil;
import com.example.common.Result;
import com.example.exception.CustomException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/files")
public class FileController {
    //当前项目的根路径
    private static final String filePath = System.getProperty("user.dir") + "\\files\\";

    @PostMapping("/upload/{type}")
    public Result upload(@PathVariable String type, MultipartFile file) {
        // 校验文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.matches(".+\\.(jpg|jpeg|png|gif)$")) {
            throw new CustomException("仅支持上传图片文件（jpg、jpeg、png、gif）", 400);
        }

        // 根据类型生成不同的文件夹路径
        String typePath = filePath + type + "\\";
        if (!FileUtil.isDirectory(typePath)) {
            // 没有目录则创建
            FileUtil.mkdir(typePath);
        }

        // 生成文件名
        String fileName = System.currentTimeMillis() + "_" + originalFilename;
        String realPath = typePath + fileName;

        // 保存文件
        try {
            FileUtil.writeBytes(file.getBytes(), realPath);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("文件上传失败", 500);
        }

        // 返回文件访问URL
        String url = "http://localhost:8080/files/download/" + type + "/" + fileName;
        return Result.success(url);
    }

    @GetMapping("/download/{type}/{filename}")
    public void download(@PathVariable String type, @PathVariable String filename, HttpServletResponse response) {
        try {
            // 根据类型生成不同的文件夹路径
            String typePath = filePath + type + "\\";
            String realPath = typePath + filename;

            // 设置响应头
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
            response.setContentType("application/octet-stream");

            // 读取文件并写入响应流
            OutputStream os = response.getOutputStream();
            byte[] bytes = FileUtil.readBytes(realPath);
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("文件下载失败", 500);
        }
    }
}
